# -*- coding: utf-8 -*-

###########################################################################
## Python code generated with wxFormBuilder (version Aug 24 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################

import wx
import wx.xrc
import wx.grid
import logging
import datetime
import re
from src.bridge.getconfdata import ConfData
from src.bridge.getsqldata import MysqlData


###########################################################################
## Class DayPortPanel
###########################################################################

class DayPortPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(746, 356),
                          style=wx.TAB_TRAVERSAL)
        self.cf = ConfData()
        self.myd = MysqlData()

        dbSizer = wx.BoxSizer(wx.VERTICAL)

        dgbSizer = wx.GridBagSizer(0, 0)
        dgbSizer.SetFlexibleDirection(wx.BOTH)
        dgbSizer.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        self.dcond_staticText = wx.StaticText(self, wx.ID_ANY, u"条件：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.dcond_staticText.Wrap(-1)
        dgbSizer.Add(self.dcond_staticText, wx.GBPosition(0, 0), wx.GBSpan(1, 1),
                     wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        dcond_choice1Choices = [wx.EmptyString, u"日期", u"禅道号"]
        self.dcond_choice1 = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, dcond_choice1Choices, 0)
        self.dcond_choice1.SetSelection(0)
        dgbSizer.Add(self.dcond_choice1, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        dcond_choice2Choices = [u"=", u"like", u"<", u">"]
        self.dcond_choice2 = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, dcond_choice2Choices, 0)
        self.dcond_choice2.SetSelection(0)
        dgbSizer.Add(self.dcond_choice2, wx.GBPosition(0, 2), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.dcond_textCtrl = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)
        dgbSizer.Add(self.dcond_textCtrl, wx.GBPosition(0, 3), wx.GBSpan(1, 2),
                     wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        self.drefer_button = wx.Button(self, wx.ID_ANY, u"更 新", wx.DefaultPosition, wx.DefaultSize, 0)

        self.drefer_button.SetDefault()
        dgbSizer.Add(self.drefer_button, wx.GBPosition(0, 5), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.dexport_button = wx.Button(self, wx.ID_ANY, u"导 出", wx.DefaultPosition, wx.DefaultSize, 0)
        dgbSizer.Add(self.dexport_button, wx.GBPosition(0, 6), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.danalysis_button = wx.Button(self, wx.ID_ANY, u"分析图", wx.DefaultPosition, wx.DefaultSize, 0)
        dgbSizer.Add(self.danalysis_button, wx.GBPosition(0, 7), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        dbSizer.Add(dgbSizer, 0, wx.EXPAND, 5)

        self.dtable_grid = wx.grid.Grid(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0)

        # Grid
        tablevalue = self._get_daydata()
        if tablevalue and len(tablevalue) > 10:
            self.dtable_grid.CreateGrid(len(tablevalue), 3)
        else:
            self.dtable_grid.CreateGrid(10, 3)
        self.dtable_grid.EnableEditing(False)
        self.dtable_grid.EnableGridLines(True)
        self.dtable_grid.EnableDragGridSize(False)
        self.dtable_grid.SetMargins(0, 0)

        # Columns
        self.dtable_grid.EnableDragColMove(False)
        self.dtable_grid.EnableDragColSize(True)
        self.dtable_grid.SetColLabelSize(30)
        self._set_col_lable()
        self.dtable_grid.SetColLabelAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)

        # Rows
        self.dtable_grid.EnableDragRowSize(True)
        self.dtable_grid.SetRowLabelSize(30)
        rows = len(tablevalue) if tablevalue else 10
        for r in range(rows):
            self.dtable_grid.SetRowSize(r, 80)
        self.dtable_grid.SetRowLabelAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)

        # Label Appearance

        # Cell Defaults
        self.dtable_grid.SetDefaultCellAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTER)
        # self.dtable_grid.Enable(False)

        dbSizer.Add(self.dtable_grid, 2, wx.ALL | wx.EXPAND, 5)
        # self._get_daydata()
        self.render_table_value(tablevalue)

        self.SetSizer(dbSizer)
        # self.Layout()
        self.SetAutoLayout(True)


        # Connect Events
        self.drefer_button.Bind(wx.EVT_BUTTON, self.refer_dayport)
        self.dexport_button.Bind(wx.EVT_BUTTON, self.exeport_dayport)
        self.danalysis_button.Bind(wx.EVT_BUTTON, self.analysis_dayport)

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def refer_dayport(self, event):
        event.GetEventObject().Disable()
        try:
            cond1 = self.dcond_choice1.GetStringSelection()
            if cond1:
                cond1 = 'daytime' if cond1 == '日期' else 'type_id'
                cond2 = self.dcond_choice2.GetStringSelection()
                condtext = self.dcond_textCtrl.GetValue()
                condition = ''
                if cond1 == 'daytime':
                    condition = "{} {} '{}'".format(cond1, cond2,
                                                    condtext) if cond2 != 'like' else "{} {} '%{}%'".format(cond1,
                                                                                                            cond2,
                                                                                                            condtext)
                elif cond1 == 'type_id':
                    if condtext.strip():
                        ty = re.findall('[A-Za-z]+', condtext) if re.findall('[A-Za-z]+', condtext) else ['']
                        dtid = re.findall('[\d]+', condtext) if re.findall('[\d]+', condtext) else ['']
                        condition = "type {} '{}' AND dataid {} '{}'".format(cond2, str(ty[0]).lower(), cond2,
                                                                             str(dtid[0]))
                    else:
                        exit(2002)
                sqldata = self.myd.sqlite_dayport_data(condition)
                try:
                    if sqldata:
                        self.dtable_grid.ClearGrid()
                        for s in range(len(sqldata)):
                            for r in range(len(sqldata)):
                                col0 = self.dtable_grid.GetCellValue(r, 0)
                                if col0 == '':
                                    self.dtable_grid.SetCellValue(r, 0, sqldata[s][0])
                                    self.dtable_grid.SetCellValue(r, 1,
                                                                  str(sqldata[s][1]).title() + '-' + str(sqldata[s][2]))
                                    break
                                elif col0 == sqldata[s][0]:
                                    text = self.dtable_grid.GetCellValue(r, 1)
                                    self.dtable_grid.SetCellValue(r, 1,
                                                                  text + ', ' + str(sqldata[s][1]).title() + '-' + str(
                                                                      sqldata[s][2]))
                                    break
                except BaseException as e:
                    logging.error(e)
            else:
                sqldata = self._get_daydata()
                self.render_table_value(sqldata)
        except BaseException as e:
            logging.error(e)
        finally:
            event.GetEventObject().Enable()
            event.Skip()

    def exeport_dayport(self, event):
        self.myd.export_sqlite_data()
        event.Skip()

    def analysis_dayport(self, event):
        event.GetEventObject().Disable()
        try:
            from src.gui.echargui import EcharP
            EcharP(self).Show(True)
        except BaseException as e:
            logging.error(e)
        finally:
            event.GetEventObject().Enable()
            event.Skip()

    def _set_col_lable(self):
        try:
            colvalues = ['日期', '事项', '合计']
            colsizes = [150, 500, 250]
            for cl in range(len(colvalues)):
                self.dtable_grid.SetColLabelValue(cl, colvalues[cl])
                self.dtable_grid.SetColSize(cl, colsizes[cl])
        except BaseException as e:
            logging.error(e)

    def _get_daydata(self):
        user = self.cf.get_one_value('ztinfo', 'user')
        try:
            enday = datetime.datetime.today() - datetime.timedelta(days=31)
            tabledata = self.myd.get_dayport_data(user, enday)
            return tabledata
        except BaseException as e:
            logging.error(e)

    def render_table_value(self, data):
        try:
            if data:
                for dt in data:
                    cellv = self.dtable_grid.GetCellValue(row=data.index(dt), col=0)
                    if cellv == '':
                        self.dtable_grid.SetCellValue(data.index(dt), 0, dt[0])
                        self.dtable_grid.SetCellAlignment(data.index(dt), 0, wx.ALIGN_CENTER, wx.ALIGN_CENTER)
                        va1 = []
                        for d in dt[1]:
                            va1.append(",".join(d))
                        self.dtable_grid.SetCellValue(data.index(dt), 1, str("\n".join(va1)))
                        self.dtable_grid.SetCellValue(data.index(dt), 2, dt[2])
        except BaseException as e:
            logging.error(e)
